import axios, { type Method, CancelTokenSource } from 'axios'
import { ElMessage } from 'element-plus'
import { getCurrentWatcher, onWatcherCleanup } from 'vue'

const baseURL = '/public'
const instance = axios.create({
  baseURL,
  timeout: 3000
})

const loading = customRef((track, trigger) => {
  let loadingCount = 0
  return {
    get() {
      track()
      return loadingCount > 0
    },
    set(value: boolean) {
      loadingCount = Math.max(0, value ? loadingCount + 1 : loadingCount - 1)
      trigger()
    }
  }
})

instance.interceptors.request.use(
  config => {
    // const token = localStorage.getItem('token')
    // if (token && config.headers) {
    //   config.headers['Authorization'] = `Bearer ${token}`
    // }
    loading.value = true
    return config
  },
  err => Promise.reject(err)
)

instance.interceptors.response.use(
  res => {
    loading.value = false

    if (res.data?.message !== 'success') {
      return Promise.reject(res)
    }

    return res.data
  },
  err => {
    loading.value = false
    return Promise.reject(err)
  }
)

type Data<T> = {
  code: number
  message: string
  data: T
  [key: string]: any
}

const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  const source: CancelTokenSource = axios.CancelToken.source()

  if (getCurrentWatcher()) {
    onWatcherCleanup(() => {
      ElMessage.error('取消了请求')
      source.cancel('请求被取消')
    })
  }

  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    cancelToken: source.token
  })
}

export { baseURL, instance, loading }
export default request
